import {
	serviceUrl
} from '../config.js'

function request(baseUrl, url, method, data, requestHeader = {}) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '努力加载中...'
		});
		data = data || null;
		uni.request({
			url: baseUrl + url,
			header: handleHeader(requestHeader),
			data: data,
			method: method,
			dataType: 'json',
			success(res) {
				uni.hideLoading();
				if (handleStatusCode(res.statusCode)) {
					resolve(res.data);
				}
			},
			fail(err) {
				console.log("请求失败", err)
				uni.showToast({
					title: '服务开了小差，请稍后再试',
					icon: 'none'
				});
				reject(err.errMsg);
			},
			complete() {}
		});
	})
}

function handleHeader(requestHeader) {
	let header = {
		// Authorization: 'Bearer ' + uni.getStorageSync('APP_TOKEN')
		"Jwt": uni.getStorageSync('userInfo')['jwt']
		// "Jwt-Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIxODQ0Nzc5MTI4MTQwMDYyNzIxIiwiaXNzIjoiU05BUkU6IiwiZXhwIjoxNzMwNjg2MjMxLCJpYXQiOjE3MzAwODE0MzF9.aLpsX-9Z5Pwlp1GtOuTU3QtpLrSv68kBQd-4Jp0pFRA"
	}
	// if (!requestHeader.hasToken) {
	// 	delete header.Authorization;
	// }
	return header;
}

function handleStatusCode(statusCode) {
	// console.log("statusCode", statusCode)
	let flag = false
	switch (statusCode) {
		case 200:
			flag = true
			break;
		case 401:
			uni.$s.gotoAuth()
			break;
		default:
			flag = true
	}
	return flag;
}

function getWithUrl(baseUrl, url, data) {
	return request(baseUrl, url, 'GET', data, null);
}

function get(url, data, headers = {}) {
	return getWithUrl(serviceUrl, url, data, headers)
}

function postWithUrl(baseUrl, url, data) {
	return request(baseUrl, url, 'POST', data, null);
}

function post(url, data, headers = {}) {
	return request(serviceUrl, url, "POST", data, headers)
}

export default {
	get,
	getWithUrl,
	post,
	postWithUrl
}